package com.sunmi.usercenter.ui.activity.fragment;

import java.lang.reflect.Type;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.bean.InputToCode;
import com.sunmi.usercenter.bean.Result;
import com.sunmi.usercenter.bean.VerificationcodeBean;
import com.sunmi.usercenter.bean.rpc.ReqCheckUserName;
import com.sunmi.usercenter.bean.rpc.ReqGetVerificationCode;
import com.sunmi.usercenter.ui.component.LoadingDialog;
import com.sunmi.usercenter.ui.component.PhoneRegisteredDialog;
import com.sunmi.usercenter.ui.component.PhoneRegisteredDialog.TwoToDoOnClickListener;
import com.sunmi.usercenter.utils.Validator;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 项目名称：Sunmi-User-Center 类描述：注册输入手机号码或者邮箱的界面 创建人：Abtswiath丶lxy 创建时间：2016/6/7
 * 11:35 修改人：longx 修改时间：2016/6/7 11:35 修改备注：
 */
public class RegisterFragment extends SuperFragment
		implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, TwoToDoOnClickListener ,TextWatcher{

	public static final String EMAIL = "email";
	public static final String PHONE = "phone";
	private View mView;
	/** 注册方式 **/
	private String registerMode;
	private String language;
	private RelativeLayout mRelBack,mRelClear;
	private TextView mTxtTitle, mTxtConsentAgreement, mTxtNext, mTxtUseMode, mTxtClause;
	private CheckBox mCheckbox;
	private boolean checkbox = true;
	private EditText mEditUsername;
	private PhoneRegisteredDialog phoneRegisteredDialog;
	private LoadingDialog mLoadingDialog;
	private int fragmentCode;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		language = getResources().getConfiguration().locale.getCountry();  // 得到当前系统的语言
		fragmentCode = Constant.mInputToCode.getFramgmentCode();// 得到是从开始界面跳转过来的还是登陆界面跳转过来的
		if (language.equals("CN")) {
			registerMode = PHONE;
		} else {
			registerMode = EMAIL;
		}
//		mCaCheModel.saveRegister(registerMode);
		initView();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		return mView = inflater.inflate(R.layout.fragment_register_input_username, container, false);
	}

	/**
	 * 初始化
	 */
	private void initView() {
		mActivity.SetStatusColorf5f5f5(); // 设置沉浸通知栏的颜色
		mLoadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.waitting));
		mRelBack = (RelativeLayout) mView.findViewById(R.id.back);
		mTxtTitle = (TextView) mView.findViewById(R.id.title);
		mTxtClause = (TextView) mView.findViewById(R.id.txt_clause);
		mTxtClause.setText(Html.fromHtml(getString(R.string.clause)));
		layoutTitle(mTxtTitle);
		mRelClear = (RelativeLayout) mView.findViewById(R.id.rel_clear);
		mTxtConsentAgreement = (TextView) mView.findViewById(R.id.txt_consent_agreement);
		mTxtNext = (TextView) mView.findViewById(R.id.btn_next);
		mTxtUseMode = (TextView) mView.findViewById(R.id.txt_use_mode);
		mCheckbox = (CheckBox) mView.findViewById(R.id.checkBox);
		mEditUsername = (EditText) mView.findViewById(R.id.txt_username);
		mEditUsername.addTextChangedListener(this);
		mTxtConsentAgreement.setText(Html.fromHtml(getResources().getString(R.string.consent_agreement)));
		mCheckbox.setChecked(true);
		mCheckbox.setOnCheckedChangeListener(this);
		String macheRegister = mCaCheModel.getRegister();
		if(!TextUtils.isEmpty(macheRegister)&&(macheRegister.equals(PHONE)||macheRegister.equals(EMAIL))){
			registerMode = macheRegister;
		}
		mTxtNext.setOnClickListener(this);
		mTxtConsentAgreement.setOnClickListener(this);
		mRelBack.setOnClickListener(this);
		mTxtClause.setOnClickListener(this);
		changeUi();
	}

	/**
	 * 切换注册方式UI
	 */
	private void changeUi() {
		mEditUsername.setText("");
		if (registerMode.equals(PHONE)) {
			mTxtTitle.setText(getString(R.string.user_phone_register));
			mEditUsername.setHint(getString(R.string.please_input_phone));
			mTxtUseMode.setText(Html.fromHtml("<u>" + getString(R.string.use_email_register) + "</u>"));
			registerMode = PHONE;
		} else {
			mTxtTitle.setText(getString(R.string.use_email_register));
			mEditUsername.setHint(getString(R.string.please_input_email));
			mTxtUseMode.setText(Html.fromHtml("<u>" + getString(R.string.user_phone_register) + "</u>"));
			registerMode = EMAIL;
		}
		mCaCheModel.saveRegister(registerMode);
		if (language.equals("CN")) {
			mTxtUseMode.setOnClickListener(this);
			mTxtUseMode.setVisibility(View.VISIBLE);
		} else {
			mTxtUseMode.setOnClickListener(null);
			mTxtUseMode.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 点击下一步按钮
	 */
	private void clickNext() {
		final String username = mEditUsername.getText().toString().trim();
		if (username.length() == 0) {
			if (registerMode.equals(EMAIL)) {
				showToast(getString(R.string.email_dont_null));
			} else {
				showToast(getString(R.string.phone_dont_null));
			}
			return;
		}
		if (registerMode.equals(EMAIL)) {
			if (!Validator.isEmail(username)) {
				showToast(getString(R.string.mail_input_error));
				return;
			}
		} else {
			if (!Validator.isMobile(username)) {
				showToast(getString(R.string.phone_input_error));
				return;
			}
		}
		if (!checkbox) {
			showToast(getString(R.string.read_consent_agreement));
			return;
		}
		mLoadingDialog.show();
		ReqCheckUserName checkUserName = new ReqCheckUserName();
		checkUserName.setUserName(username);
		mHttpController.checkUsername(checkUserName, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int i, Header[] headers, byte[] bytes) {
				String json = new String(bytes);
				Gson gson = new Gson();
				@SuppressWarnings("rawtypes")
				Result result = null;
				try {
					result = gson.fromJson(json, Result.class);
				} catch (Exception e) {
					e.printStackTrace();
				}

				if (result != null) {
					if (result.code == 1) {
						sendCode(username);
					} else {
						mLoadingDialog.dismiss();
						thisUsernameRegistered(username);

					}
				} else {
					showToast(getString(R.string.req_error));
					mLoadingDialog.dismiss();
				}
			}

			@Override
			public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
				showToast(getString(R.string.req_error));
				mLoadingDialog.dismiss();
			}
		});

	}

	/**
	 * 发送验证码
	 * 
	 * @param username
	 */
	private void sendCode(final String username) {
		ReqGetVerificationCode reqGetVerificationCode = new ReqGetVerificationCode();
		reqGetVerificationCode.setUserName(username);
		if(!getActivity().getResources().getConfiguration().locale.getCountry().equals("CN")){
			reqGetVerificationCode.setLanguage(1);
		}
		mHttpController.getVerificationCode(reqGetVerificationCode, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int i, Header[] headers, byte[] bytes) {
				String json = new String(bytes);
				Gson gson = new Gson();
				Type type = new TypeToken<Result<VerificationcodeBean>>() {
				}.getType();

				Result<VerificationcodeBean> result = null;
				try {
					result = gson.fromJson(json, type);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (result != null) {
					if (result.code == 1) {
//						VerificationcodeBean verificationcodeBean = result.getData();
//						Constant.mInputToCode.setCode(verificationcodeBean.getCode());
						Constant.mInputToCode.setSelectMode(registerMode);
						Constant.mInputToCode.setUsername(username);
						Constant.mInputToCode.setFramgment(1);
						// Constant.mInputToCode.setFramgmentCode(fragmentCode);
						openFM(new FmInfo(InputCodeFragment.class, Constant.mInputToCode));
						mEditUsername.setText("");
					} else if (result.code == 160038) {
						showToast(getString(R.string.code_send_failed));
					} else if (result.code == 160042) {
						showToast(getString(R.string.the_address_error_to_phone));
					} else if (result.code == 160039 || result.code == 160040 || result.code == 160041) {
						showToast(getString(R.string.phone_get_code_max_error));
					} else {
						showToast(getString(R.string.code_send_failed));
					}
				} else {
					showToast(getString(R.string.code_send_failed));
				}
				mLoadingDialog.dismiss();
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				showToast(getString(R.string.req_error));
				mLoadingDialog.dismiss();
			}
		});
	}

	/**
	 * 这个号码已经注册了，显示弹框
	 * 
	 * @param phone
	 */
	private void thisUsernameRegistered(String phone) {
		phoneRegisteredDialog = PhoneRegisteredDialog.createDialog(getActivity());
		if (registerMode.equals(EMAIL)) {
			phoneRegisteredDialog.setText(getString(R.string.email) + phone);
		} else {
			phoneRegisteredDialog.setText(getString(R.string.phone_number) + "+86" + phone);
		}
		phoneRegisteredDialog.setTwoOnClickListener(RegisterFragment.this, registerMode);
		user = phone;
		phoneRegisteredDialog.show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			onBack();
			mEditUsername.setText("");
			break;
		case R.id.txt_use_mode:
			if (registerMode.equals(PHONE)) {
				registerMode = EMAIL;
			} else {
				registerMode = PHONE;
			}
			changeUi();
			break;
		case R.id.btn_next:
			clickNext();
			break;
		case R.id.txt_consent_agreement:
			if (checkbox) {
				mCheckbox.setChecked(false);
			} else {
				mCheckbox.setChecked(true);
			}
			hideSoftInput();
			break;
		case R.id.txt_clause:
			openFM(new FmInfo(TermsUserFragment.class, null));
			hideSoftInput();
			break;
			case R.id.rel_clear:
				mEditUsername.setText("");
				break;
		}

	}

	private void hideSoftInput() {
		InputMethodManager imm = (InputMethodManager) getActivity()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mEditUsername.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		checkbox = isChecked;
		hideSoftInput();
	}

	@Override
	public void changePhone() {
		phoneRegisteredDialog.dismiss();
		mEditUsername.setText("");
		user = null;
	}

	private String user= null;

	@Override
	public void thisPhoneLogin() {
		openFM(new FmInfo(LoginFragment.class, user));
		phoneRegisteredDialog.dismiss();
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		if(s.length()>0){
			mRelClear.setVisibility(View.VISIBLE);
			mRelClear.setOnClickListener(this);
		}else{
			mRelClear.setVisibility(View.GONE);
			mRelClear.setOnClickListener(null);
		}
	}
}
